﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace Hive.Core.Model.Schema
{
    /// <summary>
    /// An Xml serializable representation of a descriptor.
    /// </summary>
    [Serializable]
    [XmlRoot("descriptor", Namespace = SchemaConstants.XmlNamespace)]
    [XmlType(Namespace = SchemaConstants.XmlNamespace)]
    public class DescriptorRoot
    {
        /// <summary>
        /// Creates an uninitialized descriptor root.
        /// </summary>
        public DescriptorRoot()
        {
        }

        /// <summary>
        /// Creates a descriptor root initialized from the specified descriptor.
        /// </summary>
        /// <param name="descriptor">The descriptor.</param>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="descriptor"/> is null.</exception>
        public DescriptorRoot(Descriptor descriptor)
        {
            if (descriptor == null)
                throw new ArgumentNullException("descriptor");

            Properties = descriptor.Properties.Select(x => new DescriptorProperty(x.Key, x.Value)).ToArray();
            Children = descriptor.Children.Select(x => new DescriptorChild(x.Key, x.Value)).ToArray();
        }

        /// <summary>
        /// Gets or sets an array of descriptor properties.
        /// </summary>
        [XmlElement("property", IsNullable = false)]
        public DescriptorProperty[] Properties;

        /// <summary>
        /// Gets or sets an array of descriptor children.
        /// </summary>
        [XmlElement("child", IsNullable = false)]
        public DescriptorChild[] Children;

        /// <summary>
        /// Converts this representation into a descriptor.
        /// </summary>
        /// <returns>The descriptor.</returns>
        public Descriptor ToDescriptor()
        {
            var descriptor = new Descriptor();

            if (Properties != null)
            {
                foreach (var property in Properties)
                {
                    if (property != null && property.Key != null && property.Value != null)
                        descriptor.SetProperty(property.Key, property.Value);
                }
            }

            if (Children != null)
            {
                foreach (var child in Children)
                {
                    if (child != null && child.Key != null)
                        descriptor.AddChild(child.Key, child.ToDescriptor());
                }
            }

            return descriptor;
        }
    }
}
